package m5_topic;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;

public class Consumer {
    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.64.140");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");

        Channel channel = connectionFactory.newConnection().createChannel();

        //1.定义随机队列 2.定义交换机 3.用绑定键绑定
        String queue = channel.queueDeclare().getQueue(); //由rabbitmq服务器自动命名
        channel.exchangeDeclare("topic_logs", BuiltinExchangeType.TOPIC);
        System.out.println("输入绑定键, 用空格隔开:");
        String s = new Scanner(System.in).nextLine();
        String[] split = s.split("\\s+");
        for (String key:
             split) {
            channel.queueBind(queue, "topic_logs", key);
        }


        //正常消费数据
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                String key = message.getEnvelope().getRoutingKey();
                System.out.println("收到:"+msg+" - "+key);
            }
        };

        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };

        channel.basicConsume(queue, true, deliverCallback, cancelCallback);
    }
}
